#include <cstdio>
#include <iostream>
#include <string>
#include <stack>
using namespace std;

const int maxn = 30;
struct Matrix {
  int x, y;
  Matrix(int x = 0, int y = 0):x(x), y(y) {}
} matrix[maxn];
stack<Matrix> operand_stack;

int main() {
  int n;
  cin >> n;
  
  for (int i = 0; i < n; i++) {
    string str;
    cin >> str;
    int idx = str[0] - 'A';
    cin >> matrix[idx].x >> matrix[idx].y;
  }

  string expr;
  while (cin >> expr) {
    int i = 0, exprlen = expr.length(), multi_number = 0;
    bool is_error = false;
    for ( ; i < exprlen; i++) {
      if (isalpha(expr[i])) {
        operand_stack.push(matrix[expr[i] - 'A']);
      }
      else if (expr[i] == ')') {
        Matrix m2 = operand_stack.top();
        operand_stack.pop();
        Matrix m1 = operand_stack.top();
        operand_stack.pop();
        if (!(m1.y == m2.x)) {
          is_error = true;
          break;
        }
        multi_number += m1.x * m2.x * m2.y;
        operand_stack.push(Matrix(m1.x, m2.y));
      }
    }

    if (is_error) {
      printf("error\n");
    }
    else {
      printf("%d\n", multi_number);
    }
  }
  return 0;
}
